package mysql

import (
	"fmt"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"sync"
	"week2-project/config"
	"week2-project/global"
)

var (
	err  error
	once sync.Once
)

func InitMysql() {
	app := config.AppConf.Mysql
	dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8mb4&parseTime=True&loc=Local", app.User, app.Password, app.Host, app.Port, app.Database)
	//once sync 单例模式避免浪费资源
	once.Do(func() {
		global.Db, err = gorm.Open(mysql.Open(dsn))
		if err != nil {
			fmt.Println("mysql数据库连接失败")
			return
		}
	})
	fmt.Println("mysql数据库连接成功")
	global.Db.AutoMigrate(new(Video))
}
